package com.ts.proj.json;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ts.base.controller.BaseController;
import com.ts.common.constant.ConsoleConstant;
import com.ts.common.constant.Controller2FTLConstant;
import com.ts.common.domain.UploadResponseMessage;
import com.ts.proj.entity.FileEntity;
import com.ts.proj.entity.ProjectEntity;
import com.ts.proj.entity.SystemUserEntity;
import com.ts.proj.entity.excelEntity.ProjectEntityExcel;
import com.ts.proj.service.FileService;
import com.ts.proj.service.ProjectService;
import com.ts.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;

@RestController
@Slf4j
public class CommonJson extends BaseController {

    @Value("${upload.location-pre}")
    private String locaionPre ;

    @Value("${upload.split}")
    private String split;

    @Autowired
    private FileService fileService;

    @Autowired
    private ProjectService projectService;
    /***
     * @param id 项目id
     */
    @RequestMapping("/upload-json/{proLocation}/{id}")
    public UploadResponseMessage inport(HttpServletRequest request, HttpServletResponse response,@PathVariable("proLocation") String proLocation, @PathVariable("id")Integer id){
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request;
        String detailId = "";
        if(null!=multipartRequest.getParameter("detailId")){
             detailId = multipartRequest.getParameter("detailId");
        }
        Map<String,MultipartFile> fileMap = multipartRequest.getFileMap();
        Iterator<String> iterator = fileMap.keySet().iterator();
        UploadResponseMessage uploadResponseMessage = null;
        HttpSession session = this.getRequest().getSession();
        SystemUserEntity user = JsonUtils.jsonToObject(session.getAttribute(ConsoleConstant.SESSIONUSER).toString(),SystemUserEntity.class);

        boolean flag = false;
        while(iterator.hasNext()){
            MultipartFile multipartFile = fileMap.get(iterator.next());
            ProjectEntity entity = projectService.findById(id);
            String uuid = "";
            if(null!=entity.getId()){
                uuid = entity.getUuid();
            }
            String fileName = proLocation+"_"+multipartFile.getOriginalFilename();
            String fileFolder = locaionPre + uuid + split + proLocation + split;

            if(-1==id){
                fileName = multipartFile.getOriginalFilename();
                fileFolder = locaionPre + user.getUsername() + split;
            }
            File folder = new File(fileFolder);
            if(!folder.exists()){
                folder.mkdirs();
            }
            File dest = new File(fileFolder + fileName);
            try {
                multipartFile.transferTo(dest);
                //记入数据库
                FileEntity fileEntity = new FileEntity();
                fileEntity.setProjId(String.valueOf(entity.getId()));
                fileEntity.setUserId(user.getId());
                fileEntity.setBelongTo(user.getBelongTo());
                fileEntity.setFileName(dest.getName());
                fileEntity.setState(proLocation);
                fileEntity.setUuid(uuid.toString());
                fileEntity.setDocType(multipartFile.getName());
                fileEntity.setProjName(multipartFile.getOriginalFilename());
                fileEntity.setErrorDetailId(detailId);
                fileService.save(fileEntity);
            } catch (IOException e) {
                return  new UploadResponseMessage("300", e.getMessage(), "error");
            }
            flag = true;
        }

        if(flag){
            return new UploadResponseMessage("200", "上传成功", "success");
        }else

        return new UploadResponseMessage("200", "长传失败", "normal");
    }


    @RequestMapping("/common/getExcelData")
    public String getExcelData(){
        //和upload匹配起来：/upload-json/ruku/-1

        HttpSession session = this.getRequest().getSession();
        SystemUserEntity user = JsonUtils.jsonToObject(session.getAttribute(ConsoleConstant.SESSIONUSER).toString(),SystemUserEntity.class);
        String templatePath = locaionPre + user.getUsername() + split;
//        String templatePath = Controller2FTLConstant.WINDOWPATH + Controller2FTLConstant.FILEABSTRACTPATH + user.getUsername() + Controller2FTLConstant.WINDOWSPLIT;
//        String templatePath = "/software/upload/" + user.getUsername() + "/";
        List<ProjectEntityExcel> excelList = new ArrayList<>();
        File file = new File(templatePath);
        if(file.isDirectory()){
            File[] files = file.listFiles();
            //如果不存在，直接返回
            if(0==files.length){
                ProjectEntityExcel projectEntityExcel = new ProjectEntityExcel();
                projectEntityExcel.setProCompany("没有上传文件，请重新上传！");
                excelList.add(projectEntityExcel);
            }else{
                for(int i=0;i<files.length;i++){
                    File temp = files[i];
                    if(temp.getName().equals("template.xls")){
                        excelList = FileUtil.importExcel(templatePath + temp.getName(), 1, 1, ProjectEntityExcel.class);
                        break;
                    }
                }
            }
        }
        if(0 == excelList.size()){
            ProjectEntityExcel projectEntityExcel = new ProjectEntityExcel();
            projectEntityExcel.setProCompany("上传的文件，名称不能修改，只能为：template.xls");
            excelList.add(projectEntityExcel);
        }
        return JsonUtils.objectToJson(excelList);

    }

    @RequestMapping("/project-import-save")
    public String projectImportSave(){

        PageData pageData = this.getPageData();
        List<JSONObject> rows = JsonUtils.jsonToObject(pageData.getString("rows"), List.class);
        List<ProjectEntity> projectEntities = new ArrayList<>();
        List<ProjectEntity> sameProjectEntites = new ArrayList<>();
        HttpSession session = this.getRequest().getSession();
        SystemUserEntity user = JsonUtils.jsonToObject(session.getAttribute(ConsoleConstant.SESSIONUSER).toString(),SystemUserEntity.class);
        for(JSONObject jsonObject : rows){
            ProjectEntity projectEntity = JSONObject.toJavaObject(jsonObject, ProjectEntity.class);
            if(null == projectEntity.getProId() || "".equals(projectEntity.getProId())){
                projectEntity.setProId(KeyUtils.getKey());
            }

            List<ProjectEntity> all = projectService.findProjectByProName(projectEntity.getProName());
            if(0==all.size()){
                projectEntity.setBelongTo(user.getBelongTo());
                projectEntity.setUserId(user.getId());
                projectEntity.setProState(0);
                projectEntity.setProLocation("ruku");
                projectEntity.setUuid(UuidUtil.get32UUID());
                projectEntities.add(projectEntity);
            }else if(0!=all.size()){
                sameProjectEntites.add(projectEntity);
            }
        }
        projectService.saveAll(projectEntities);

        String result = "上传成功";
        if(0!=sameProjectEntites.size()){
            result = "名称为：";
            for(ProjectEntity entity : sameProjectEntites){
                result += "\""+ entity.getProName()+ "\""+"、";
            }
            result = result.trim().substring(0,result.length()-1);
            result += "。的项目已经存在！";
        }
        return result;
    }
}
